﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;

namespace Ha666.Redis.Test
{
    public partial class Form1 : Form
    {

        private static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private Trade trade = null;
        private CSharpType type = null;

        public Form1()
        {
            InitializeComponent();
            trade = new Trade
            {
                Tid = 78943561326512345,
                Title = "村有地在有有厅地",
                Status = "TRADE_FINISHED",
                Created = new DateTime(2014, 05, 31, 01, 01, 01),
                Modified = new DateTime(2015, 05, 01, 00, 00, 00),
                SellerNick = "要肝在十月份地的",
                BuyerNick = "tbha666"
            };
            type = new CSharpType
            {
                Int0 = -2147483648,
                Int1 = 2147483647,
                Long0 = -9223372036854775808,
                Long1 = 9223372036854775807,
                String0 = "奠%基@塔*顶(地)伯_佣-兵+模=压! 、枯\"干' 遥A在一起  使#@用者?？?~?",
                String1 = "{43D51482-9F09-4CA1-A3CD-94AB37D97989}",
            };
        }

        /// <summary>
        /// 查询当前时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            StringKey key = new StringKey("ha666");
            List<string> list = key.Time(0);
            lblTime.Text = string.Format("{0}.{1}", GetTime(list[0]).ToString("yyyy-MM-dd HH:mm:ss"), list[1]);
        }

        public DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// 设置/获取一个对象
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                //ProtobufMapSet key = new ProtobufMapSet("ha666_map");
            }
            catch (Exception exception)
            {
                MessageBox.Show(string.Format("出错了：{0}", exception.Message));
            }
        }

        /// <summary>
        /// 设置一个Map对象
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            ProtobufMapSet key = new ProtobufMapSet("ha666_map");
            key.HSet(0, "trade", trade);
        }

        /// <summary>
        /// 获取一个Map对象
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            ProtobufMapSet key = new ProtobufMapSet("ha666_map");
            Trade trade = key.Hget<Trade>(0, "trade");
            MessageBox.Show(string.Format("标题：{0}", trade.Title));
        }

        /// <summary>
        /// 设置一个Map字符串
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            ProtobufMapSet key = new ProtobufMapSet("ha666_map");
            key.HSet(0, "currtime", DateTime.Now.ToString("HH:mm:ss.fff"));
        }

        /// <summary>
        /// 获取一个Map字符串
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            ProtobufMapSet key = new ProtobufMapSet("ha666_map");
            string time = key.Hget<string>(0, "currtime");
        }

        /// <summary>
        /// 设置一个List到Set中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            list.Add("a");
            list.Add("b");
            list.Add("c");
            list.Add("d");
            list.Add("e");
            list.Add("f");
            StringSet key = new StringSet("ha666_set");
            key.Sadds(0, list);
        }

        /// <summary>
        /// 从Set中获取List
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button8_Click(object sender, EventArgs e)
        {
            Stopwatch time = new Stopwatch();
            time.Start();
            for (int i = 0; i < 100000; i++)
            {
                StringSet key = new StringSet("ha666_set");
                List<string> list = key.Smember<string>(0);
            }
            time.Stop();
            MessageBox.Show("获取100000次，耗时：" + time.ElapsedMilliseconds + "毫秒！");
        }

        /// <summary>
        /// 设置一个带过期时间的对象
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button9_Click(object sender, EventArgs e)
        {
            Stopwatch time = new Stopwatch();
            time.Start();
            StringKey key = new StringKey("ha666_set_ex");
            key.Set(0, "1234567890", 6000, null, null);
            time.Stop();
            MessageBox.Show("耗时：" + time.ElapsedMilliseconds + "毫秒！");
        }

        /// <summary>
        /// 获取可过期的对象
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button10_Click(object sender, EventArgs e)
        {
            Stopwatch time = new Stopwatch();
            time.Start();
            StringKey key = new StringKey("ha666_set_ex");
            var obj = key.Get<string>(0);
            var ttl = key.TTL(0);
            time.Stop();
            MessageBox.Show("耗时：" + time.ElapsedMilliseconds + "毫秒！过期时间:" + ttl);
        }

        /// <summary>
        /// Key加增量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button11_Click(object sender, EventArgs e)
        {
            StringKey key = new StringKey("ha666_incrby");
            long result = key.Incrby(20, 0);
            MessageBox.Show(result.ToString());
        }

        /// <summary>
        /// 检查一个对象是否存在
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button12_Click(object sender, EventArgs e)
        {
            StringKey key = new StringKey("ha666_EXISTS");
            key.Set(0, "ha666_EXISTS", 600, null, null);

            bool exists = key.Exists(0);

            MessageBox.Show(exists == true ? "key存在" : "key不存在");
        }

        /// <summary>
        /// 将给定 key 的值设为 value 并返回 key 的旧值(old value)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button13_Click(object sender, EventArgs e)
        {
            StringKey key1 = new StringKey("ha666_RENAME");
            key1.Set(0, "1234567890", 600, null, null);
            var obj1 = key1.Get<string>(0);
            var ttl1 = key1.TTL(0);

            key1.Rename(0, "ha666_New_RENAME");

            StringKey key2 = new StringKey("ha666_New_RENAME");
            var obj2 = key2.Get<string>(0);
            var ttl2 = key2.TTL(0);
            MessageBox.Show(string.Format("对象：{0}过期时间{1}", obj2, ttl2));
        }

        private void button15_Click(object sender, EventArgs e)
        {
            try
            {
                ProtobufKey key1 = new ProtobufKey("csharpkey");
                key1.Set(0, type);
                CSharpType type1 = key1.Get<CSharpType>(0);
                if (type1 != null)
                {
                    MessageBox.Show("添加成功：" + type1.Long1);
                }
                else
                {
                    MessageBox.Show("没有添加成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 将给定 key 的值设为 value ，并返回 key 的旧值(old value)(当 key 存在但不是字符串类型时，返回一个错误。)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button14_Click(object sender, EventArgs e)
        {
            StringKey key = new StringKey("ha666_GETSET");
            key.Set(0, "888888", 6000, null, null);

            ////如果是带过期时间的，生存时间丢失
            var oldValue = key.GetSet<string>(0, "999999");

            var ttl1 = key.TTL(0);

            MessageBox.Show(string.Format("key旧值：{0}过期时间{1}", oldValue, ttl1));
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                RedisHost.Disconnect();
                Logger.Info("【Form1_FormClosing】关闭了所有的redis连接。");
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("【Form1_FormClosing】关闭所有的redis连接出错：{0}。", ex);
            }
        }

        private void button16_Click(object sender, EventArgs e)
        {
            try
            {
                StringKey key = new StringKey("ha666");
                long memorySize = key.InfoMemory(0);
                MessageBox.Show("内存：" + memorySize);
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败：" + ex.Message);
            }
        }

        private void button17_Click(object sender, EventArgs e)
        {
            try
            {
                StringKey key = new StringKey("ha666");
                int clientSize = key.InfoClient(0);
                MessageBox.Show("连接数：" + clientSize);
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败：" + ex.Message);
            }
        }
    }
}
